package com.ruoyi.law_model.knowledge.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.HttpClientUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.law_model.knowledge.Const;
import com.ruoyi.law_model.knowledge.domain.DocumentSplit;
import com.ruoyi.law_model.knowledge.mapper.DocumentSplitMapper;
import com.ruoyi.law_model.knowledge.service.IDocumentSplitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 存储文档分段信息Service业务层处理
 *
 * @author lihuayong
 * @date 2025-01-10
 */
@Service
public class DocumentSplitServiceImpl implements IDocumentSplitService
{
    private static final Logger log = LoggerFactory.getLogger(DocumentSplitServiceImpl.class);
    @Autowired
    private DocumentSplitMapper documentSplitMapper;
    @Value("${knowledge.doc_split_host}")
    private String doc_split_host;

    @Value("${knowledge.doc_split_add_url}")
    private String doc_split_add_url;

    @Value("${knowledge.doc_split_del_url}")
    private String doc_split_del_url;

    @Value("${knowledge.doc_split_update_url}")
    private String doc_split_update_url;

    @Value("${knowledge.doc_split_cookie}")
    private String doc_split_cookie;

    /**
     * 查询存储文档分段信息
     *
     * @param docSegId 存储文档分段信息主键
     * @return 存储文档分段信息
     */
    @Override
    public DocumentSplit selectDocumentSplitByDocSegId(Long docSegId)
    {
        return documentSplitMapper.selectDocumentSplitByDocSegId(docSegId);
    }

    /**
     * 查询存储文档分段信息列表
     *
     * @param documentSplit 存储文档分段信息
     * @return 存储文档分段信息
     */
    @Override
    public List<DocumentSplit> selectDocumentSplitList(DocumentSplit documentSplit)
    {
        return documentSplitMapper.selectDocumentSplitList(documentSplit);
    }

    /**
     * 新增存储文档分段信息
     *
     * @param documentSplit 存储文档分段信息
     * @return 结果
     */
    @Override
    public int insertDocumentSplit(DocumentSplit documentSplit)
    {
        // 拆分文件内容
        Map<String,String> params = new HashMap<>();
        params.put("doc_content",documentSplit.getSegContent());
        params.put("file_name","摘录自一段话");
        Const.DOC_MODA_HEADERS.put("Cookie",doc_split_cookie);
        String docResult = HttpClientUtil.doPostJson(doc_split_host+doc_split_add_url, JSONObject.toJSONString(params), Const.DOC_MODA_HEADERS);
        if(StringUtils.isEmpty(docResult)){
            log.info("添加分段失败，返回结果为空");
            return 0;
        }
        // 还原成json对象
        JSONArray jsonArray = JSONArray.parseArray(docResult);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            DocumentSplit split = new DocumentSplit();
            split.setKlId(documentSplit.getKlId());
            split.setSegContent(jsonObject.getString("seg_content"));
            split.setEmbedId(jsonObject.getString("embed_id"));
            split.setCreatedAt(new Date());
            split.setCreatedBy(documentSplit.getCreatedBy());
            split.setUpdatedAt(new Date());
            split.setUpdatedBy(documentSplit.getUpdatedBy());
            documentSplitMapper.insertDocumentSplit(split);
        }
        return 1;
    }
    @Override
    public int saveDocumentSplit(DocumentSplit documentSplit)
    {
        return documentSplitMapper.insertDocumentSplit(documentSplit);
    }

    /**
     * 修改存储文档分段信息
     *
     * @param documentSplit 存储文档分段信息
     * @return 结果
     */
    @Override
    public int updateDocumentSplit(DocumentSplit documentSplit)
    {
        //先更新向量数据库
        DocumentSplit documentSplitFromDB = this.selectDocumentSplitByDocSegId(documentSplit.getDocSegId());
        Map<String,String> params = new HashMap<>();
        params.put("doc_split_id",documentSplitFromDB.getEmbedId());
        params.put("doc_split_content",documentSplit.getSegContent());
        Const.DOC_MODA_HEADERS.put("Cookie",doc_split_cookie);
        String docResult = HttpClientUtil.doPostJson(doc_split_host+doc_split_update_url,JSONObject.toJSONString(params), Const.DOC_MODA_HEADERS);
        if(!"1\n".equals(docResult)){
            log.info("更新分段失败，返回结果为：{}",docResult);
            return 0;
        }
        return documentSplitMapper.updateDocumentSplit(documentSplit);
    }

    /**
     * 批量删除存储文档分段信息
     *
     * @param docSegIds 需要删除的存储文档分段信息主键
     * @return 结果
     */
    @Override
    public int deleteDocumentSplitByDocSegIds(Long[] docSegIds)
    {
        //先删除向量数据库
        DocumentSplit documentSplit = this.selectDocumentSplitByDocSegId(docSegIds[0]);
        List<String> embedIds = new ArrayList<>();
        embedIds.add(documentSplit.getEmbedId());
        Map<String,List<String>> params = new HashMap<>();
        params.put("doc_split_ids",embedIds);
        Const.DOC_MODA_HEADERS.put("Cookie",doc_split_cookie);
        String docResult = HttpClientUtil.doPostJson(doc_split_host+doc_split_del_url,JSONObject.toJSONString(params), Const.DOC_MODA_HEADERS);
        if(!"1\n".equals(docResult)){
            log.info("删除分段失败，返回结果为：{}",docResult);
            return 0;
        }
        return documentSplitMapper.deleteDocumentSplitByDocSegIds(docSegIds);
    }

    /**
     * 删除存储文档分段信息信息
     *
     * @param docSegId 存储文档分段信息主键
     * @return 结果
     */
    @Override
    public int deleteDocumentSplitByDocSegId(Long docSegId)
    {
        return documentSplitMapper.deleteDocumentSplitByDocSegId(docSegId);
    }
}
